package com.zixi.ai.framework.dao;

import jakarta.persistence.EntityManager;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

import java.io.Serializable;

/**
 * @author mqiqe
 */
public class MyRepositoryFactoryBean<R extends JpaRepository<T, I>, T, I extends Serializable>
		extends JpaRepositoryFactoryBean<R, T, I> {

	public MyRepositoryFactoryBean(Class<? extends R> repositoryInterface) {
		super(repositoryInterface);
	}

	@NotNull
	@Override
	protected RepositoryFactorySupport createRepositoryFactory(@NotNull EntityManager em) {
		return new MyRepositoryFactory(em);
	}

	// 创建一个内部类，该类不用在外部访问
	private static class MyRepositoryFactory extends JpaRepositoryFactory {
		private final EntityManager em;
		public MyRepositoryFactory(EntityManager em) {
			super(em);
			this.em = em;
		}
		// 设置具体的实现类是BaseRepositoryImpl
		@NotNull
		@Override
		protected JpaRepositoryImplementation<?, ?> getTargetRepository(RepositoryInformation information,
																		@NotNull EntityManager entityManager) {
			return new BaseRepositoryImpl<>(information.getDomainType(), em);
		}

		// 设置具体的实现类的class
		@NotNull
		@Override
		protected Class<?> getRepositoryBaseClass(@NotNull RepositoryMetadata metadata) {
			return BaseRepositoryImpl.class;
		}
	}
}